﻿/////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009 Eric Bowen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
// associated documentation files (the "Software"), to deal in the Software without restriction, including 
// without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the 
// following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial 
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Author's blog: http://blog.scrappydog.com
// Updated source code available:  http://scrappydb.codeplex.com
/////////////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Configuration;
using System.Diagnostics;
using System.Web.Caching;
using Amazon.SimpleDB;
using Amazon.SimpleDB.Model;
using NLog;
using ScrappyDB;
using ScrappyDB.BaseClasses;

namespace ScrappyDB.Utilities
{
    public class Domains
    {
        private static readonly Logger Log = LogManager.GetCurrentClassLogger();

        public Cache WebCache = null;
 
        public Domains (Cache cache)
        {
            WebCache = cache;
        }

        public string EnsureDomain<T>(T entity) where T : class
        {
            var domainName = EntityHelper.GetDomainName<T>(entity);
            EnsureDomain(domainName);

            return domainName;
        }

        public void EnsureDomain(string domainName)
        {
            if (!DomainExists(domainName))
                CreateDomain(domainName);
        }

        public  void CreateDomain(string domainName)
        {
            try
            {
                var db = new Db(WebCache);
                var service = db.Service;

                if (!DomainExists(domainName))
                {
                    var request = new CreateDomainRequest { DomainName = domainName };

                    CreateDomainResponse response = service.CreateDomain(request);

                    //this is a WARN because it's unussual... might be a sign of an issue...
                    Log.Warn("ScrappyDB.CreateDomain: Domain: {0}", domainName);

                    if (response.IsSetResponseMetadata())
                        Utility.TraceResponse(response.ResponseMetadata, response.ToXML());
                }
            }
            catch (Exception ex)
            {
                Log.Error("ERROR: CreateDomain: {1} {0}", ex.Message, domainName);
                throw;
            }
        }

        public  bool DomainExists(string domainName)
        {
            var cacheKey = "DomainExists(" + domainName + ")";

            if (WebCache != null)
            {
                if (WebCache.Get(cacheKey) != null)
                {
                    var c = (bool) WebCache.Get(cacheKey);
                    if (c == true)
                    {
                        Log.Debug("CACHE HIT: {0}", cacheKey);

                        return c;
                    }
                }
            }

            var db = new Db(WebCache);
            var service = db.Service;

            bool result = false;
            var request = new ListDomainsRequest();
            ListDomainsResponse response = service.ListDomains(request);

            if (response.IsSetListDomainsResult())
            {
                ListDomainsResult listDomainsResult = response.ListDomainsResult;
                if (listDomainsResult.DomainName.Contains(domainName))
                    result = true;
            }

            Log.Debug("ScrappyDB.DomainExists: Domain: {0}", domainName);
            if (response.IsSetResponseMetadata())
                Utility.TraceResponse(response.ResponseMetadata, response.ToXML());

            if (WebCache != null)
            {
                //cache this forever... domains shouldn't ever go away
                WebCache.Add(cacheKey, true, null, 
                    DateTime.MaxValue,
                    System.Web.Caching.Cache.NoSlidingExpiration,
                    CacheItemPriority.Default, null);

                Log.Debug("CACHE ADD:  {0}", cacheKey);
            }
            return result;
        }

        public  void DeleteDomain(string tableName)
        {
            var db = new Db(WebCache);
            var service = db.Service;

            if (!DomainExists(tableName))
            {
                //TODO:
                throw new NotImplementedException();
            }
        }
    }
}